package com.ws.base.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class MD5Util {

    private MD5Util() {
    }

    private static class SingletonHolder {
        private final static MD5Util INSTANCE = new MD5Util();
    }

    public static MD5Util getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public String getFileMD5(File file) {
        String md5 = null;
        FileChannel ch = null;
        FileInputStream in = null;

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            ch = in.getChannel();
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,
                    0, file.length());
            messagedigest.update(byteBuffer);
            BigInteger bigInt = new BigInteger(1, messagedigest.digest());
            md5 = bigInt.toString(16);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != ch) {
                    ch.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return md5;
    }
}
